﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace CheckMemcached
{
    public class CheckSocket
    {
        private static bool IsConnectionSuccessful = false;
        private static Exception socketexception;
        private readonly ManualResetEvent TimeoutObject = new ManualResetEvent(false);
        /// <summary>
        /// Socket连接请求
        /// </summary>
        /// <param name="remoteEndPoint">网络端点</param>
        public SocketEnum AsyncConnect(Server server)
        {
            TimeoutObject.Reset();
            IPAddress ipa = IPAddress.Parse(server.Host);
            IPEndPoint ipep = new IPEndPoint(ipa, server.Port);
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            socket.BeginConnect(ipep, new AsyncCallback(CallBackMethod), socket);
            //阻塞当前线程
            if (TimeoutObject.WaitOne(5, false))
            {
                if (IsConnectionSuccessful)
                {
                    return SocketEnum.Success;
                }
                else
                {
                    return SocketEnum.Exception;
                }
            }
            else
            {
                socket.Close();
                return SocketEnum.TimeOut;
            }
        }
        //--异步回调方法
        private void CallBackMethod(IAsyncResult asyncresult)
        {
            try
            {
                IsConnectionSuccessful = false;
                Socket socket = asyncresult.AsyncState as Socket;
                if (socket != null)
                {
                    socket.EndConnect(asyncresult);
                    IsConnectionSuccessful = true;
                }
            }
            catch (Exception ex)
            {
                socketexception = ex;
            }
            finally
            {
                TimeoutObject.Set();
            }
        }

        /// <summary>
        /// 同步连接
        /// </summary>
        /// <param name="server"></param>
        /// <returns></returns>
        public SocketEnum Connect(Server server)
        {
            try
            {
                IPAddress ipa = IPAddress.Parse(server.Host);
                IPEndPoint ipep = new IPEndPoint(ipa, server.Port);
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Connect(ipep);
                socket.Send(Encoding.ASCII.GetBytes("stats\r\n"));
                string result = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = socket.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
                result += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                socket.Close();
                if (EventLog.SourceExists("CheckMemcached") && GetConfig.IsWriteSuccessEventLog())
                {
                    EventLog.WriteEntry("CheckMemcached", result, EventLogEntryType.Information, 1);
                }
                return SocketEnum.Success;
            }
            catch (Exception ex)
            {
                if (EventLog.SourceExists("CheckMemcached"))
                {
                    EventLog.WriteEntry("CheckMemcached", ex.Message, EventLogEntryType.Error, 1);
                }
                return SocketEnum.Exception;
            }
        }
    }
}
